#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>

#include <pigpio.h>

/*
  dht11 read
  gcc -o dht11 dht11.c -lpigpio -lpthread
  sudo ./dht11
*/


typedef unsigned char uint8;
typedef unsigned int  uint16;
typedef unsigned long uint32;
 
int pinNumber = 7;
uint32 databuf;
  
uint8 readSensorData(void)
{
    uint8 crc; 
    uint8 i;
    gpioSetMode(pinNumber, PI_OUTPUT); // set mode to output
    gpioWrite(pinNumber, 0); // output a low level
    gpioDelay(25000);
    gpioWrite(pinNumber, 1); // output a high level
    gpioDelay(20);

    gpioSetMode(pinNumber, PI_INPUT); // set mode to input
    gpioSetPullUpDown(pinNumber, PI_PUD_UP);
 
    gpioDelay(27);
    if (gpioRead(pinNumber) == 0){
        
        while (!gpioRead(pinNumber));//wait to high
        for (i = 0; i < 32; i++)
        {
            while (gpioRead(pinNumber));//data clock start
            while (!gpioRead(pinNumber));//data start
            gpioDelay(30);
            databuf *= 2;
            if (gpioRead(pinNumber) == 1) //1
            {
                databuf++;
            }
        }
 
        for (i = 0; i < 8; i++)
        {
            while (gpioRead(pinNumber));//data clock start
            while (!gpioRead(pinNumber));//data start
            gpioDelay(30);
            crc *= 2;  
            if (gpioRead(pinNumber) == 1){
                crc++;
            }
        }
        return 1;
    }else{
        return 0;
    }
}
  
int main(void)
{
    printf("PIN:%d\n", pinNumber);
 
    if (gpioInitialise() < 0) {
        printf("Setup pigpio failed!");
        return 1;
    }

    printf("Starting...\n");
    uint8 n = 0;
    while (n < 200){
        gpioSleep(PI_TIME_RELATIVE, 3, 0);
        if (readSensorData())
        {
            printf("Sensor data read ok!\n");
            printf("RH:%d.%d\n", (databuf >> 24) & 0xff, (databuf >> 16) & 0xff); 
            printf("TMP:%d.%d\n", (databuf >> 8) & 0xff, databuf & 0xff);
            databuf = 0;
        }else{
            printf("Sensor dosent ans!\n");
            databuf = 0;
        }
        n++;
    }
	gpioTerminate();
    return 0;
}

